package com.usian.admin.gatway.filter;

import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.beans.Transient;
import java.util.function.Consumer;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//2.判断当前的请求是否为登录，如果是，直接放行
        if(request.getURI().getPath().contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }

//3.获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        if (StringUtils.isBlank(token)){
            String json="{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        Claims claims= AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);
        if (i ==-1 || i==0){
            Integer id=(Integer) claims.get("id");
            ServerHttpRequest  newRequest=  request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId",id+"");
                }
            }).build();
            exchange.mutate().request(newRequest).build();
        }
        return chain.filter(exchange);
    }
    /**
     * 优先级设置
     * 值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
